package com.xn.monitor.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by yangshoujun on 2017/7/29 下午1:30.
 */
public class SerializeUtil {

    private static Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    public static <T extends Serializable> byte[] serialize(T  obj) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            byte[] serialized = baos.toByteArray();
            return serialized;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        return null;
    }

    public static <T> T unSerialize(byte[] serialized) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
            ObjectInputStream ois = new ObjectInputStream(bis);
            T unSerialized = (T) ois.readObject();
            return unSerialized;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
